package com.hancher.common.androidutil;

import android.app.ActivityManager;
import android.content.Context;

import com.hancher.common.base.BaseApplication;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.List;

/**
 * 作者 : Hancher ytu_shaoweijie@163.com <br/>
 * 时间 : 2023/5/13 10:57 <br/>
 * 描述 : 手机内存工具类
 */
public class MemoryUtil {
    public enum Unit {
        BYTE,
        KB,
        MB,
        GB,
        TB
    }

    /**
     * 获得内存使用情况
     * @param unit 获取的大小
     * @param keepDigit 保留位数
     * @return [未使用, 已使用, 总计]
     */
    public static List<BigDecimal> getMemory(Unit unit, int keepDigit) {
        ActivityManager.MemoryInfo mi = getMemoryInfo();
        BigDecimal avail = new BigDecimal(mi.availMem);
        BigDecimal total = new BigDecimal(mi.totalMem);
        BigDecimal used = total.subtract(avail);
        avail = changeMemoryDigit(avail, Unit.BYTE, unit, keepDigit);
        total = changeMemoryDigit(total, Unit.BYTE, unit, keepDigit);
        used = changeMemoryDigit(used, Unit.BYTE, unit, keepDigit);
        return Arrays.asList(avail, used, total);
    }

    private static BigDecimal changeMemoryDigit(BigDecimal data, Unit srcUnit, Unit originUnit, int keepDigit) {
        BigDecimal d = new BigDecimal("1024").pow(originUnit.ordinal() - srcUnit.ordinal());
        return data.divide(d, keepDigit, RoundingMode.HALF_UP);
    }

    private static ActivityManager.MemoryInfo getMemoryInfo() {
        ActivityManager am = (ActivityManager) BaseApplication.getInstance().getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        return mi;
    }

}
